package com.lg.common.exception;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lg.system.log.service.LogService;
import com.lg.utils.HttpServletUtils;
import com.lg.utils.R;
import com.lg.wechat.utils.ReturnCode;

import me.chanjar.weixin.common.exception.WxErrorException;

@ControllerAdvice
public class ExceptionHandle {
	private static final String ERROR_PATH = "error/";
	private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
	
	@Autowired
	LogService logService; 
    @ExceptionHandler(value = GlobalException.class)
    @ResponseBody
    public R HandleGlobal(GlobalException e){
    	 logService.saveLog(e);
    	 return e.getR();
    }
    
    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public Object handleAuthorizationException(AuthorizationException e, HttpServletRequest request) {
        logger.error(e.getMessage(), e);
        logService.saveLog(e);
        if (HttpServletUtils.jsAjax(request)) {
            return R.error(403, "未授权");
        }
        return new ModelAndView(ERROR_PATH+"403");
    }
    
    @ExceptionHandler(WxErrorException.class)
    @ResponseBody
    public Object wxErrorException(WxErrorException e, HttpServletRequest request) {
    	logger.error("微信公总号捕捉异常");
    	logger.error(ReturnCode.get(e.getError().getErrorCode()));
    	return R.error(ReturnCode.get(e.getError().getErrorCode()));
    }
    
    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Object handleException(Exception e, HttpServletRequest request) {
    	 logger.error("[系统异常]"+e.getMessage(),e);
    	 logService.saveLog(e);
    	 if (HttpServletUtils.jsAjax(request)) {
             return R.error(500, "系统异常,请联系管理员!");
         }
        return new ModelAndView(ERROR_PATH+"500");
    }
    
    
}
